package com.wwj.aiAnswer.controller;

import cn.hutool.core.io.FileUtil;
import com.wwj.aiAnswer.service.TrainService;
import com.wwj.aiAnswer.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

@RestController
@Slf4j
@RequestMapping("/api")
public class AnswerController {

    @Resource
    private TrainService trainService;

    /**
     * 上传并训练模型
     * @param file 上传文件对象
     * @param authorizationCode 授权码
     * @return R
     * @throws Exception IO异常
     */
    @PostMapping("/upload")
    private R<Object> upload(@RequestParam MultipartFile file,@RequestParam("authorizationCode") String authorizationCode) throws Exception {
        // 验证授权码
        if (!"1234".equals(authorizationCode)) {
            return R.error(401, "授权码验证失败", null);
        }
        // 获取上传路径将上传的文件传入本地
        String uploadPath = "C:\\CodeDevelopment\\trainTXT\\model.txt";
        // 创建该路径的IO流删除旧的model.txt
        File oldFile = new File(uploadPath);
        // 删除旧的文件
        FileUtil.del(oldFile);
        // MultipartFile对象不为空
        if (!file.isEmpty()) {
            //  创建IO流
            File localFile = new File(uploadPath);
            try {
                // 将上传的文件存入该对象的路径
                file.transferTo(localFile);
            } catch (IOException e) {
                e.printStackTrace();
                return R.error(402, "IO操作错误", null);
            }
            // 调用训练模型方法判断是否操作成功
            if (trainService.trainModel(uploadPath)) return R.ok(200, "成功", null);
        }
        return R.error(403, "失败", null);
    }

    /**
     * 前端点击发送后台得出回复结果
     * @param question 前端请求的问题
     * @return R
     * @throws Exception IO异常
     */
    @GetMapping("/question")
    private R<String> question(@RequestParam("question") String question) throws Exception {
        return R.ok(200, "成功", trainService.answerForAI(question));
    }
}
